<?php

use Biz\model\IkeaActivity\IkeaActivityJoinRecordModel;

class SaveAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_REGISTER;

    /**
     * @throws \Exception
     */
    public function main()
    {
        $currentUid = $this->uid;
        $taskId = trim($this->getRequest()->getPost('task_id', 0));
        $taskDetail = trim($this->getRequest()->getPost('task_detail', ''));
        $type = trim($this->getRequest()->getPost('type', 1));
        \Doraemon\tools\Log::info('IkeaActivity/Save', compact('currentUid', 'taskId', 'taskDetail', 'type'));
        if ($taskId == 0) {
            throw new Exception('参数错误');
        }
        //判断活动开始时间
        $taskMap = array_column(IkeaActivityJoinRecordModel::TASK_MAP, null, 'task_id');
        if (date('Ymd') < $taskMap[$taskId]['start_time'] && IkeaActivityJoinRecordModel::TYPE_TASK == $type) {
            throw new Exception($taskMap[$taskId]['toast']);
        }
        $map = [
            'uid' => $currentUid,
            'task_id' => $taskId,
            'type' => $type,
        ];

        $info = IkeaActivityJoinRecordModel::getByWhere($map);
        if (empty($info)) {
            IkeaActivityJoinRecordModel::insertData(array_merge($map, ['task_detail' => $taskDetail]));
        } else {
            if ($taskId == 5 && IkeaActivityJoinRecordModel::TYPE_TASK == $type) {
                IkeaActivityJoinRecordModel::updateDataByWhere(['task_detail' => $taskDetail], $map);
            }

        }

        $this->setSuccess([], self::API_CODE_SUCCES);

    }
}